package MusicLandscape.util.io;

import MusicLandscape.util.MyFormatter;

import java.io.FileWriter;
import java.io.IOException;

/**
 * Generic class for writing objects to files in a specific format.
 *
 * @param <T>
 * @author Jonas Altrock (ew20b126@technikum-wien.at)
 * @version 1
 * @since ExerciseSheet06
 */
public class MyWriter<T> {
    /**
     * The underlying stream.
     * <p>
     * Cannot be null.
     */
    protected FileWriter out;

    /**
     * The format in which data is written to file.
     * <p>
     * Cannot be null.
     */
    private final MyFormatter<T> theFormat;

    /**
     * Constructs a MyWriter with a specific target file and format.<br>
     * In case null objects are passed to this constructor IllegalArgumentException is thrown.
     *
     * @param file      the file to which to save the data.
     * @param theFormat the format in which to store the data.
     */
    public MyWriter(FileWriter file, MyFormatter<T> theFormat) {
        if (file == null) {
            throw new IllegalArgumentException("expected non-null FileWriter");
        }
        if (theFormat == null) {
            throw new IllegalArgumentException("expected non-null MyFormatter");
        }

        this.out = file;
        this.theFormat = theFormat;
    }

    /**
     * Closes the underlying stream.<br>
     * All exceptions are ducked.
     */
    public void close() throws IOException {
        out.flush();
        out.close();
    }

    /**
     * Writes a single object to the underlying file.
     * <p>
     * The object passed to this method is written to file in the format of this MyWriter.<br>
     * A newline character is appended at the end of data. This method handles all IOExceptions that might occur and
     * returns false in such a case.
     *
     * @param t the object to be written to file
     * @return true if the object was written to file successfully, false otherwise.
     */
    public boolean put(T t) {
        try {
            out.write(theFormat.format(t) + "\n");
        } catch (IOException e) {
            return false;
        }
        return true;
    }
}
